/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.metadata.service.dev.core.entity.validate;

import com.inspur.edp.lcm.metadata.spi.entity.MetadataDependencyDetail;
import com.inspur.edp.metadata.service.dev.core.entity.GspMetadataCache;
import lombok.Getter;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;


/**
 * 邻接矩阵的顶点类
 *
 * @author sunhongfei01
 */
public class MetadataVertex {

    /**
     * 在元数据关系图中,以元数据id作为图中顶点的唯一标识
     * -- GETTER --
     * 返回顶点的标识
     */
    @Getter
    private final String metadataId;

    /**
     * 记录顶点内容
     * -- GETTER --
     * 返回顶点的内容
     */
    @Getter
    private final GspMetadataCache content;

    /**
     * 这个顶点对应的子顶点<br>
     * 如果为有向图，则代表以这个顶点为起点的结束顶点
     */
    private final Set<MetadataRelateEdge> edges = new HashSet<>();


    /**
     * 创建顶点
     *
     * @param metadataId   这个顶点的标识
     * @param content 这个顶点的内容
     */
    public MetadataVertex(String metadataId, GspMetadataCache content) {
        this.metadataId = metadataId;
        this.content = content;
    }

    //下面与顶点的标识相关

    /**
     * 根据顶点的标识确定是否是同一个顶点
     */
    @Override
    public boolean equals(Object otherVertex) {
        boolean result;
        //如果otherVertex为空或者类不同，直接返回false
        if (otherVertex == null || getClass() != otherVertex.getClass()) {
            return false;
        }
        //根据MetadataId确定是否是同一个顶点
        result = metadataId.equals(((MetadataVertex) otherVertex).getMetadataId());
        return result;
    }

    @Override
    public int hashCode() {
        return Objects.hash(metadataId);
    }

    //下面与顶点的边相关

    /**
     * 将这个顶点与endVertex连接
     *
     * @param endMetadataId 待连接顶点MetadataId
     * @param content  边的内容
     * @return 如果顶点已经与endVertex连接，那么将会返回false<br>
     * 如果顶点没有与endVertex相连，则互相连接，返回true
     */
    protected boolean connect(String endMetadataId, MetadataDependencyDetail content) {
        MetadataRelateEdge metadataRelateEdge = new MetadataRelateEdge(this.getMetadataId(), endMetadataId, content);
        return edges.add(metadataRelateEdge);
    }

    public Set<MetadataRelateEdge> getEdges() {
        return new HashSet<>(edges);
    }
}
